import { DBObject } from './DBObject'
export enum ProductState {
    onsale = 1,
    offsale = 2
}
export enum DurationUnit {
    Year = 'y',
    Month = 'M',
    Week = 'w',
    Day = 'd',
    Second = 's'
}
export class Product extends DBObject {
    public no?: string
    public title?: string
    public price: number = 0
    public duration?: number
    public durationUnit: DurationUnit = DurationUnit.Year
    public durationString?: string
    public description?: string
    public stock: number = 0;
    public state: ProductState = ProductState.onsale;
    public stateString?: string
    public sku?: string
    public remarks?: string
    constructor(product: any) {
        super(8);
        Object.assign(this, product);
        this.createDurationString();
        this.createStateString();
        if (this.stock <= 0) {
            this.state = ProductState.offsale;
        }
    }
    public update() {
        super.update();
        this.createDurationString();
        this.createStateString();
    }
    public reduceStock() {
        return new Promise((resolve, reject) => {
            if (this.stock > 0) {
                this.stock--;
                if (this.stock <= 0) {
                    this.state = ProductState.offsale;
                }
                this.update();
                resolve();
            } else {
                reject(new Error("outstock"));
            }
        })
    }
    public increaseStock() {
        this.stock++;
        if (this.stock > 0) {
            this.state = ProductState.onsale;
        } else {
            this.state = ProductState.offsale;
        }
    }
    private createDurationString() {
        let char = ''
        if (this.duration) {
            switch (this.durationUnit) {
                case DurationUnit.Year:
                    char = '年'
                    break;
                case DurationUnit.Month:
                    char = '月'
                    break;
                case DurationUnit.Week:
                    char = '周'
                    break;
                case DurationUnit.Day:
                    char = '天'
                    break;
                case DurationUnit.Second:
                    char = '秒'
                    break;
                default:
                    char = ''
            }
            this.durationString = this.duration + char;
        }
    }
    private createStateString() {
        if (this.state === ProductState.onsale) {
            this.stateString = '在售'
        } else {
            this.stateString = '下架'
        }
    }

}